package cn.git.agent;

import cn.git.agent.loader.AgentClassLoader;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/** 
 * @description: 插件启动类
 * @program: bank-credit-sy
 * @author: lixuchun
 * @create: 2024-12-26
 */
public class PluginBootstrap {

    /**
     * 加载所有插件
     * 因为是自定义路径下的jar包，所以需要手动加载
     *  1.获取到agent-jar的路径
     *  2.使用自定义类加载器加载插件
     *
     * @return
     */
    public List<AbstractClassEnhancePluginDefine> loadPlugins() {
        AgentClassLoader.initDefaultClassLoader();

        PluginResourceResolver resourceResolver = new PluginResourceResolver();
        List<URL> resources = resourceResolver.getResources();

        if (resources == null && resources.size() == 0) {
            System.out.println("no plugins define file git-plugins.def found !");
            return new ArrayList<>();
        }

        for (URL resource : resources) {
            try {
                PluginCfg.INSTANCE.load(resource.openStream());
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("load plugins define file git-plugins.def failed !");
            }
        }

        // 拿到全类目，通过反射获取到实例对象，使用AbstractClassEnhancePluginDefine进行接收
        List<PluginDefine> pluginClassList = PluginCfg.INSTANCE.getPluginClassList();
        List<AbstractClassEnhancePluginDefine> pluginDefineList = new ArrayList<>();
        for (PluginDefine pluginDefine : pluginClassList) {
            try {
                AbstractClassEnhancePluginDefine plugin = (AbstractClassEnhancePluginDefine) Class.forName(
                        pluginDefine.getDefineClass(),
                        true,
                        AgentClassLoader.getDefaultClassLoader()
                ).newInstance();
                pluginDefineList.add(plugin);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("load plugin define class " + pluginDefine.getDefineClass() + " failed !");
            }
        }
        return pluginDefineList;
    }
}
